/*
 * @Author: Clark
 * @Email: haixuanwoTxh@gmail.com
 * @Date: 2023-01-05 10:49:05
 * @LastEditors: Clark
 * @LastEditTime: 2023-01-05 11:00:09
 * @Description: file content
 */

#include "apue.h"

static volatile sig_atomic_t sigflag;   // set nonzero by sig handler
static sigset_t newmask, oldmask, zeromask;

static void sig_usr(int signo)
{
    sigflag = 1;
}

void TELL_WAIT()
{
    if (signal(SIGUSR1, sig_usr) == SIG_ERR)
    {
        err_sys("signal(SIGUSR1) error");
    }

    if (signal(SIGUSR2, sig_usr) == SIG_ERR)
    {
        err_sys("signal(SIGUSR2) error");
    }

    sigemptyset(&zeromask);
    sigemptyset(&newmask);

    sigaddset(&newmask, SIGUSR1);
    sigaddset(&newmask, SIGUSR2);

    if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
    {
        err_sys("SIG_BLOCK error");
    }
}

void TELL_PARENT(pid_t pid)
{
    kill(pid, SIGUSR2);     // tell parent we're done
}

void WAIT_PARENT()
{
    while (0 == sigflag)
    {
        sigsuspend(&zeromask);  // and wait for parent
    }

    sigflag = 0;

    // reset signal mask to original value
    if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
    {
        err_sys("SIG_SETMASK error");
    }
}

void TELL_CHILD(pid_t pid)
{
    kill(pid, SIGUSR1);
}

void WAIT_CHILD()
{
    while (0 == sigflag)
    {
        sigsuspend(&zeromask);  // and wait for child
    }
    sigflag = 0;

    // reset signal mask to original value
    if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
    {
        err_sys("SIG_SETMASK error");
    }
}
